package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.result.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @Description: 角色表处理器类
 * @Author: 伍家钰
 * @Date: 2020/7/11 0:44
 * @Version: 1.0
 */
@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleServiceImpl;
    @Autowired
    private IPermissionService permissionServiceImpl;

    /**
     * 删除操作
     *
     * @param id:用户输入的id
     * @return :返回封装的JSON对象
     */
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        try {
            if (id != null) {
                roleServiceImpl.delete(id);
            }
            return new JsonResult();
        } catch (Exception e) {
            return new JsonResult(false, "删除失败,请联系管理员!");
        }
    }

    /**
     * 去新增或者修改页面
     *
     * @param id:用户传入的员工id
     * @param model:将查询的数据共享到共享域中
     * @return :跳转视图到:/WEB-INF/views/role/input.jsp页面
     */
    @RequestMapping("/input")
    public String input(Model model, Long id) {
        model.addAttribute("permission", permissionServiceImpl.selectAll());
        if (id != null) {
            // 查询出来的role对象里边封装了permission对象数据,可以此来实现回显
            Role role = roleServiceImpl.selectById(id);
            model.addAttribute("role", role);
        }
        return "role/input";
    }

    /**
     * 新增或者修改
     *
     * @param role:前端传入的角色对象
     * @return :重定向到:/role/list.do
     */
    @RequestMapping("/saveOrUpdate")
    public String update(Role role, Long[] ids) {
        if (role.getId() != null) {
            roleServiceImpl.update(role, ids);
        } else {
            roleServiceImpl.save(role, ids);
        }
        //让浏览器重新发送一次请求
        return "redirect:/role/list.do";
    }

    /**
     * 分页查询操
     *
     * @param model:将查询的数据共享到共享域中
     * @param qo:用户传入的查询参数对象
     * @return :跳转视图到:/WEB-INF/views/role/list.jsp页面
     */
    @RequestMapping("/list")
    public String query(Model model, QueryObject qo) {
        PageInfo<Role> pageInfo = roleServiceImpl.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "role/list";
    }

}
